package com.leisure.interceptors;

import com.leisure.utils.JWTUtil;
import com.leisure.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * ClassName: LoginInterceptor
 * Package: com.leisure.interceptors
 * Description:
 *
 * @Author: MyLeisureLife
 * @Date: 2024/6/8:16:53:20 星期六
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // first : Get the `Authorization` data for the request header
        String token = request.getHeader("Authorization");
        // second : Verify that the token data for `Authorization` is correct and has not been modified
        try {
            Map<String, Object> stringObjectMap = JWTUtil.parseJWT(token);
            System.out.println(stringObjectMap);
            ThreadLocalUtil.set(stringObjectMap);
            // third ： if the verification data is normal, no interception will be performed
            return true;
        }catch (Exception e){
            // fourth : if the verification fail, the request will be intercepted and response status code will be set to 401
            response.setStatus(401);
            return false;
        }
   }
}
